<template>
  <view class="reserve-page">

    <view class="block">
    <!-- 店铺名称 -->
    <view class="shop-name">
      <text>{{ shopName }}</text>
    </view>

    <!-- 桌台信息 -->
    <view class="table-info">
      <text class="table-number">{{ tableNumber }}</text>
      <text class="table-type">中式台球</text>
    </view>
    </view>

    <!-- 滑动时间选择器 -->
    <view class="scroll-time-picker">
      <view class="time-label">预约时间段</view>
      <!-- 新增：日期选择 -->
      <view class="date-picker-container">
        <picker
            mode="selector"
            range-key="label"
            :range="dateOptions"
            :value="selectedDateIndex"
            @change="onDateChange"
        >
          <view class="date-item">
            <text>选择日期: {{ selectedDateLabel || '请选择' }}</text>
          </view>
        </picker>
      </view>

      <view class="time-selectors">
        <picker
            mode="time"
            :value="startTime"
            @change="onStartTimeChange"
        >
          <view class="time-item">
            <text>开始时间: {{ startTime || '请选择' }}</text>
          </view>
        </picker>

        <!-- 结束时间选择器 -->
        <picker
            mode="time"
            :value="endTime"
            @change="onEndTimeChange"
        >
          <view class="time-item">
            <text>结束时间: {{ endTime || '请选择' }}</text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 预约金和收费规则 -->
    <view class="payment-info">
      <view class="deposit">
        <text>预约金</text>
        <text>60 元</text>
      </view>
      <view class="charge-rule" @click="showChargeRule">
        <text>收费规则</text>
        <text>0.46元/分钟 > </text>
      </view>
    </view>

    <!-- 立即预约按钮 -->
    <view class="reserve-button-container">
      <view class="button-wrapper">
       <text class="deposit-text">￥60</text>
       <button class="reserve-button"  @click="onReserve">立即预约</button>
      </view>
    </view>

    <!-- 支付方式弹窗 -->
    <view v-if="showPaymentDialog" class="payment-dialog">
      <view class="dialog-overlay" @click.self="closePaymentDialog"></view>
      <view class="dialog-content">
        <view class="dialog-header">
          <text>请选择支付方式</text>
          <image src="/static/img/close.png" mode="aspectFit" @click="closePaymentDialog" class="close-icon"></image>
        </view>
        <view class="payment-methods">
          <view v-for="method in paymentMethods" :key="method.id" class="method-item" @click="selectPaymentMethod(method.id)">
            <image class="method-icon" :src="method.icon" mode="aspectFit" />
            <text class="method-name">{{ method.name }}</text>
            <image v-if="selectedPaymentMethod === method.id" class="checkmark" src="/static/img/checkmark.png" mode="aspectFit" />
          </view>
        </view>
        <button class="confirm-btn" @click="submitOrder">确定</button>
      </view>
    </view>

  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  data() {
    const now = new Date();
    const hour = now.getHours();
    const minute = now.getMinutes();
    const defaultTime = `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`;

    // 生成未来 7 天的日期数组
    const dateOptions = [];
    for (let i = 0; i < 7; i++) {
      const date = new Date(now);
      date.setDate(now.getDate() + i);
      const label = i === 0 ? '今天' : i === 1 ? '明天' : this.formatDate(date, 'short');
      dateOptions.push({
        value: this.formatDate(date, 'yyyy-mm-dd'),
        label: label
      });
    }

    return {
      tableNumber: '',
      shopName: '',
      selectedPaymentMethod: 'wechat',
      startTime: defaultTime,
      endTime: defaultTime,
      showPaymentDialog: false,
      price: 0,

      paymentMethods: [
        { id: 'wechat', name: '微信支付', icon: '/static/img/wechat-pay.png' },
        { id: 'alipay', name: '支付宝支付', icon: '/static/img/alipay-pay.png' },
        { id: 'balance', name: '余额支付', icon: '/static/img/balance.png' }
      ],

      // 新增：日期相关数据
      dateOptions, // 存储未来7天日期选项
      selectedDateIndex: 0, // 默认选择第一个（今天）
      selectedDateLabel: '今天', // 显示标签
      selectedDateValue: this.formatDate(now, 'yyyy-mm-dd'), // 实际值
    };
  },
  computed: {
    ...mapState('balanceAndPoints', ['balance']),
  },
  onLoad(options) {
    this.tableNumber = options.tableNumber;
    this.shopName = options.shopName;
    this.userBalance = this.balance
    // 页面加载时设置 endTime 默认值为 startTime + 1h
    this.setEndTime(this.startTime);
    this.price = parseFloat(options.price) || 0; // 如果为空则默认设为 0
  },
  methods: {
    ...mapActions('balanceAndPoints', ['updateBalance']),

    showChargeRule() {
      // 弹出收费规则详情
      uni.showToast({ title: '查看收费规则', icon: 'none' });
    },
    // 格式化日期
    formatDate(date, formatType) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');

      if (formatType === 'short') {
        return `${month}-${day}`;
      } else {
        return `${year}-${month}-${day}`;
      }
    },

    // 日期选择事件
    onDateChange(e) {
      const index = e.detail.value;
      const selected = this.dateOptions[index];
      this.selectedDateIndex = index;
      this.selectedDateLabel = selected.label;
      this.selectedDateValue = selected.value;

      // 可以在这里更新时间选择器的默认值为所选日期的当前时间
      const now = new Date();
      const todayStr = this.formatDate(new Date(), 'yyyy-mm-dd');
      const selectedDateStr = selected.value;

      // 如果是今天，保留当前时间
      if (todayStr === selectedDateStr) {
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        this.startTime = `${currentHour < 10 ? '0' + currentHour : currentHour}:${currentMinute < 10 ? '0' + currentMinute : currentMinute}`;
      } else {
        // 否则设置为当天 09:00
        this.startTime = '09:00';
      }

      this.setEndTime(this.startTime); // 更新结束时间为开始时间+1小时
    },
    formatTimeValue(value) {
      let hour, minute;

      if (typeof value === 'string') {
        // 如果是字符串（如 H5、微信小程序）
        [hour, minute] = value.split(':').map(Number);
      } else if (Array.isArray(value)) {
        // 如果是数组（如 App）
        const hourStep = value[0];
        const minuteStep = value[1];
        hour = hourStep;
        minute = minuteStep * 5; // 每 5 分钟一档
      } else {
        // 默认错误处理
        return '请选择';
      }

      return `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`;
    },
    onStartTimeChange(e) {
      this.startTime = this.formatTimeValue(e.detail.value);
      this.setEndTime(this.startTime);
    },
    onEndTimeChange(e) {
      this.endTime = this.formatTimeValue(e.detail.value);
    },
    setEndTime(startTime) {
      const [h, m] = startTime.split(':').map(Number);
      let newHour = h + 1;
      if (newHour >= 24) newHour -= 24;

      this.endTime = `${newHour < 10 ? '0' + newHour : newHour}:${m < 10 ? '0' + m : m}`;
    },
    onReserve() {
      if (!this.reserveTimeLimit(this.startTime, this.endTime)) {
        return;
      }
      if (this.selectedPaymentMethod === 'balance') {
        const deposit = 60;
        if (this.balance < deposit) {
          uni.showModal({
            title: '余额不足',
            content: '您的余额不足，是否前往充值？',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({ url: '/pages/tabbar/tabbar-1-detail/vip' }); // 跳转到充值页面
              }
            }
          });
          return;
        }
      }
      this.showPaymentDialog = true;
    },
    selectPaymentMethod(id) {
      this.selectedPaymentMethod = id;
    },
    closePaymentDialog() {
      this.showPaymentDialog = false;
    },
    submitOrder() {
      const selectedDateTime = new Date(`${this.selectedDateValue}T${this.startTime}:00`);
      const scheduledStartTime = selectedDateTime.getTime(); // 获取时间戳

      const newOrder = {
        orderId: 'ORD' + Math.floor(Math.random() * 1000000),
        shopName: this.shopName,
        tableNumber: this.tableNumber,
        startTime: this.startTime,
        endTime: this.endTime,
        createdTime: new Date().toLocaleString(),
        status: 'pendingUse',
        paymentType: this.selectedPaymentMethod, //记录支付方式
        price: parseFloat(this.price),
        scheduledStartTime: scheduledStartTime // 使用完整时间戳
      };

      // 立即标记球桌为“已占用”
      let occupiedTables = uni.getStorageSync('occupiedTables') || [];
      if (!occupiedTables.includes(newOrder.tableNumber)) {
        occupiedTables.push(newOrder.tableNumber);
        uni.setStorageSync('occupiedTables', occupiedTables);
      }

      // 可以在这里跳转或执行实际支付操作
      if (newOrder.paymentType === 'wechat') {
        // 调用微信支付接口
      } else if (newOrder.paymentType === 'alipay') {
        // 调用支付宝支付接口
      }  else if (newOrder.paymentType === 'balance') {
        const deposit = 60;
        if (this.balance < deposit) {
          uni.showToast({ title: '余额不足', icon: 'none' });
          return;
        }
        // 真正执行余额支付逻辑
        const newBalance = this.balance - deposit;
        this.updateBalance(newBalance);
        uni.showToast({ title: `已使用余额支付 ${deposit} 元`, icon: 'none' });
      }
      uni.$emit('newPendingOrder', newOrder); // 发送事件
      uni.showToast({ title: '预约成功', icon: 'success' });
      this.showPaymentDialog = false;

      // 通知所有监听者刷新球桌状态
      uni.$emit('updateOccupiedTables');
      // 在这里添加返回上一页的逻辑
      uni.navigateBack({
        delta: 2 // 返回上一页，即 shop.vue
      });
    },
    reserveTimeLimit(startTime, endTime) {
      if (!startTime || !endTime) {
        uni.showToast({ title: '请选择完整的时间段', icon: 'none' });
        return false;
      }

      const [startHour, startMinute] = startTime.split(':').map(Number);
      const [endHour, endMinute] = endTime.split(':').map(Number);

      // 转换为分钟数
      const startTotalMin = startHour * 60 + startMinute;
      const endTotalMin = endHour * 60 + endMinute;

      const diffMin = endTotalMin - startTotalMin;

      if (diffMin <= 0) {
        uni.showToast({ title: '结束时间不能早于开始时间', icon: 'none' });
        return false;
      }

      if (diffMin > 4 * 60) {
        uni.showToast({ title: '预约时间段不能超过4小时', icon: 'none' });
        return false;
      }

      return true;
    }

  }
};
</script>

<style>
page{
  background-color: #eaeaea;
}
</style>

<style scoped>
.reserve-page {
  background-color: #eaeaea;
}

.block{
  padding: 20rpx;
  background-color: white;
}

.shop-name {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.table-info {
  background-color: #fffbe6;
  padding: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.table-number {
  font-size: 48rpx;
  color: #333;
  font-weight: bold;
}

.table-type {
  font-size: 32rpx;
  color: #000000;
}

.scroll-time-picker {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;
}

.time-label {
  font-size: 32rpx;
  color: #000000;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.time-selectors {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.time-item {
  padding: 15rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #f9f9f9;
  color: #333;
}

.payment-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;
}

.deposit {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
  color: black;
  font-weight: bold;
}

.charge-rule {
  display: flex;
  justify-content: space-between;
  color: #000000;
  font-weight: bold;

}

.reserve-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx 60rpx; /* 上下左右间距，20rpx 是顶部的小距离 */
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
  display: flex;
  justify-content: space-between;
  align-items:  flex-start;
}

.button-wrapper {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  justify-content: space-between;
  width: 100%;
  max-width: 750rpx;
}

.deposit-text {
  flex: 2;
  min-width: 150rpx; /* 防止被压缩得太小 */
  font-size: 60rpx;
  color: #000000;
  margin-left: 20rpx;
  margin-bottom: 60rpx;
}

.reserve-button {
  width: auto;
  min-width: 240rpx;
  height: 100rpx;
  line-height: 100rpx;
  padding: 0 60rpx;
  background-color: #ffc107;
  color: #000000;
  border-radius: 20rpx;
  font-size: 40rpx;
  margin-left: auto; /* 如果需要按钮靠右 */
  margin-bottom: 60rpx;
}

.payment-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.5);
}

.dialog-overlay {
  width: 100%;
  height: 100%;
}

.dialog-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
}

.close-icon {
  width: 40rpx;
  height: 40rpx;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 15rpx;
  background-color: #f9f9f9;
}

.method-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 30rpx;
}

.method-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.checkmark {
  width: 40rpx;
  height: 40rpx;
}

.confirm-btn {
  margin-top: 40rpx;
  background-color: #ff3c00;
  color: white;
  font-size: 30rpx;
}

.date-picker-container {
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.date-item {
  padding: 15rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #f9f9f9;
}
</style>
